﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.huigo.Framework.Passport;
using com.huigo.Framework.ServiceUtils;
using System.IO;
using Net.SourceForge.Koogra.Excel;
using System.Configuration;

namespace com.huigo.B2B.Web
{
    public partial class hx : System.Web.UI.Page
    {
        protected string operType = string.Empty;
        protected string response = string.Empty;
        protected bool IsLogin = true;
        protected long CustId = 0;
        public decimal AlipayRate
        {
            get
            {
                return Convert.ToDecimal(ConfigurationManager.AppSettings["AlipayRate"]);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (CustPassport.ChkCookieLogin())
            {
                CustId = CustPassport.GetCookieUserId();
            }
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;

            if (!string.IsNullOrEmpty(f("oper")))
            {
                operType = f("oper");
            }
            else
            {
                operType = q("oper");
            }

            //未登录时调用的方法
            if (!CustPassport.ChkCookieLogin())
            {
                switch (operType)
                {
                    case "checkUserName":
                        response = checkUserName();
                        break;
                    case "checkUserEmail":
                        response = checkUserEmail();
                        break;
                    case "custLogin":
                        response = custLogin();
                        break;
                    case "checkCode":
                        response = checkCode();
                        break;
                }
            }
            else
            {
                switch (operType)
                {
                    case "CreateOrderInfo":
                        CreateOrderInfo();
                        break;
                    case "UploadAir":
                        UploadAirExcelFile();
                        break;
                    case "UploadTravel":
                        UploadTravelExcelFile();
                        break;
                    case "CancelOrder":
                        response = CancelOrder();
                        break;
                    case "CancelPolicy":
                        response = CancelPolicy();
                        break;
                    case "policyproblem":
                        GetPolicyProblem();
                        break;
                    case "GetCityListByProvinceId":
                        GetCityListByProvinceId();
                        break;
                    case "AddInvoiceOrder":
                        response = AddInvoiceOrder();
                        break;
                    case "GetOrderAddress":
                        GetOrderAddress();
                        break;
                    case "GetOrderFedex":
                        GetOrderFedex();
                        break;
                    case "GetSupplement":
                        GetSupplement();
                        break;
                }
            }

            Response.Write(response);
            Response.End();

        }
        /// <summary>
        /// 检查用户名是否已经存在
        /// </summary>
        /// <returns></returns>
        private string checkUserName()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string userName = q("userName");
            List<RequestFuncParams> artList = new List<RequestFuncParams>();
            artList.Add(new RequestFuncParams("userName", userName));
            BaseService service = new BaseService();
            ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.CHECK_USER_NAME, artList);
            if (parser != null && parser.RowsCount > 0)
            {
                msg = "exists";
            }
            else
            {
                msg = "suc";
            }
            return string.Format(resultFormat, msg);
        }
        /// <summary>
        /// 检查邮箱是否存在
        /// </summary>
        /// <returns></returns>
        private string checkUserEmail()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string userEmail = Request.QueryString["userEmail"];
            List<RequestFuncParams> list = new List<RequestFuncParams>();
            list.Add(new RequestFuncParams("email", userEmail));
            BaseService service = new BaseService();
            ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.CHECK_USER_EMAIL, list);
            if (parser != null && parser.RowsCount > 0)
            {
                msg = "exists";
            }
            else
            {
                msg = "suc";
            }
            return string.Format(resultFormat, msg);
        }
        /// <summary>
        /// 前台用户登录
        /// </summary>
        /// <returns></returns>
        private string custLogin()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string custName = Request.QueryString["custName"];
            string custPwd = Request.QueryString["custPwd"];
            if (!string.IsNullOrEmpty(custName) && !string.IsNullOrEmpty(custPwd))
            {
                if (CustPassport.Login(custName, custPwd, 14))
                {
                    msg = "suc";
                }
                else
                {
                    msg = "err";
                }
            }
            return string.Format(resultFormat, msg);
        }
        /// <summary>
        /// 检查验证码
        /// </summary>
        /// <returns></returns>
        private string checkCode()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string code = Request.QueryString["code"];
            HttpCookie cookie = Request.Cookies["vvvvalidccccode"];
            if (code == cookie.Value)
            {
                msg = "suc";
            }
            else
            {
                msg = "err";
            }
            return string.Format(resultFormat, msg);
        }
        /// <summary>
        /// 提交订单
        /// </summary>
        /// <returns></returns>
        private void CreateOrderInfo()
        {
            string[] arrList = HttpContext.Current.Request.Form.GetValues("arrList[]");
            string productId = f("productId");
            string orderId = string.Empty;
            string orderNo = string.Empty;
            bool isNull = false;
            int productQuota = 0;
            int productAgeMin = 0;
            int productAgeMax = 0;
            decimal totalPrice = 0;
            decimal productPrice = 0;
            int insType = 0;

            if (!string.IsNullOrEmpty(productId))
            {
                List<RequestFuncParams> requestList = new List<RequestFuncParams>();
                requestList.Add(new RequestFuncParams("productId", productId));
                BaseService service = new BaseService();
                ParserXml parserXml = service.RequestEntryService(Dict.ERequestFunc.GET_PRODUCT_INFO_BY_PRODUCT_ID, requestList);
                if (parserXml.RowsCount > 0)
                {
                    productQuota = Convert.ToInt32(parserXml["ProductQuota", 0]);
                    productAgeMin = Convert.ToInt32(parserXml["ProductAgeMin", 0]);
                    productAgeMax = Convert.ToInt32(parserXml["ProductAgeMax", 0]);
                    productPrice = Convert.ToDecimal(parserXml["ProductSettlePrice", 0]);
                    insType = Convert.ToInt16(parserXml["ProductTypeFid", 0]);
                }
            }
            if (arrList != null && arrList.Length > 0)
            {
                List<string> policyList = new List<string>();
                //判断险种
                switch (insType)
                {
                    case (int)Dict.InsType.Air:
                        string airHolderName = string.Empty;
                        string airHolderType = string.Empty;
                        string airHolderNo = string.Empty;
                        string airHolderBirth = string.Empty;
                        string airHolderGender = string.Empty;


                        string airInsuredName = string.Empty;
                        string airInsuredType = string.Empty;
                        string airInsuredNo = string.Empty;
                        string airInsuredBirth = string.Empty;
                        string airInsuredGender = string.Empty;

                        string airInsuredTel = string.Empty;
                        string airFromPeriod = string.Empty;//起期日期
                        string airCount = string.Empty;//购买份数      
                        string airFlightNo = string.Empty;
                        string airEmail = string.Empty;
                        int airHolderAge = 0;
                        int airInsuredAge = 0;
                        for (int i = 0; i < arrList.Length; i += 15)
                        {
                            airHolderName = arrList[i];
                            airHolderType = arrList[i + 1];
                            airHolderNo = arrList[i + 2];
                            airHolderBirth = arrList[i + 3];
                            airHolderGender = arrList[i + 4];

                            airInsuredName = arrList[i + 5];
                            airInsuredType = arrList[i + 6];
                            airInsuredNo = arrList[i + 7];
                            airInsuredBirth = arrList[i + 8];
                            airInsuredGender = arrList[i + 9];
                            airInsuredTel = arrList[i + 10];
                            airFromPeriod = arrList[i + 11];
                            airCount = arrList[i + 12];
                            airFlightNo = arrList[i + 13];
                            airEmail = arrList[i + 14];
                            if (!string.IsNullOrEmpty(airHolderName) && !string.IsNullOrEmpty(airHolderType) && !string.IsNullOrEmpty(airHolderNo) && com.loto.Common.TypeParse.isDate(airHolderBirth) && !string.IsNullOrEmpty(airHolderGender) && !string.IsNullOrEmpty(airInsuredNo) && !string.IsNullOrEmpty(airInsuredName) && !string.IsNullOrEmpty(airInsuredType) && com.loto.Common.TypeParse.isDate(airInsuredBirth) && !string.IsNullOrEmpty(airInsuredGender) && com.loto.Common.TypeParse.isDate(airFromPeriod) && com.loto.Common.TypeParse.IsNumeric(airCount))
                            {
                                airHolderAge = DateTime.Now.Year - Convert.ToDateTime(airHolderBirth).Year;
                                airInsuredAge = DateTime.Now.Year - Convert.ToDateTime(airInsuredBirth).Year;
                                if ((airHolderAge > productAgeMin || airHolderAge == productAgeMin) && (airHolderAge < productAgeMax || airHolderAge == productAgeMax))
                                {
                                    if ((airInsuredAge > productAgeMin || airInsuredAge == productAgeMin) && (airInsuredAge < productAgeMax || airInsuredAge == productAgeMax))
                                    {
                                        if (productQuota != 0 && Convert.ToInt16(airCount) > productQuota)
                                        {
                                            isNull = false;
                                            response = "count";
                                            break;
                                        }
                                        else
                                        {
                                            isNull = true;
                                            string policyRow = "{0}^^^^{1}^^^^{2}^^^^{3}^^^^{4}^^^^{5}^^^^{6}^^^^{7}^^^^{8}^^^^{9}^^^^{10}^^^^{11}^^^^{12}^^^^{13}^^^^{14}";
                                            policyRow = string.Format(policyRow, airHolderName, airHolderType, airHolderNo, airHolderBirth, airHolderGender, airInsuredName, airInsuredType, airInsuredNo, airInsuredBirth, airInsuredGender, airInsuredTel, airFromPeriod, airCount, airFlightNo, airEmail);
                                            policyList.Add(policyRow);
                                            totalPrice += Convert.ToInt32(airCount) * productPrice;
                                        }
                                    }
                                    else
                                    {
                                        isNull = false;
                                        response = "age";
                                        break;
                                    }
                                }
                                else
                                {
                                    isNull = false;
                                    response = "age";
                                    break;
                                }
                            }
                            else
                            {
                                response = "absence";
                                isNull = false;
                                break;
                            }
                        }
                        break;
                    case (int)Dict.InsType.Travel:
                        string travelHolderName = string.Empty;
                        string travelHolderType = string.Empty;
                        string travelHolderNo = string.Empty;
                        string travelHolderBirth = string.Empty;
                        string travelHolderGender = string.Empty;


                        string travelInsuredName = string.Empty;
                        string travelInsuredType = string.Empty;
                        string travelInsuredNo = string.Empty;
                        string travelInsuredBirth = string.Empty;
                        string travelInsuredGender = string.Empty;

                        string travelInsuredTel = string.Empty;
                        string travelFromPeriod = string.Empty;//起期日期
                        string travelCount = string.Empty;//购买份数      
                        string travelLine = string.Empty;
                        string travelEmail = string.Empty;
                        int travelHolderAge = 0;
                        int travelInsuredAge = 0;
                        for (int i = 0; i < arrList.Length; i += 15)
                        {
                            travelHolderName = arrList[i];
                            travelHolderType = arrList[i + 1];
                            travelHolderNo = arrList[i + 2];
                            travelHolderBirth = arrList[i + 3];
                            travelHolderGender = arrList[i + 4];

                            travelInsuredName = arrList[i + 5];
                            travelInsuredType = arrList[i + 6];
                            travelInsuredNo = arrList[i + 7];
                            travelInsuredBirth = arrList[i + 8];
                            travelInsuredGender = arrList[i + 9];
                            travelInsuredTel = arrList[i + 10];
                            travelFromPeriod = arrList[i + 11];
                            travelCount = arrList[i + 12];
                            travelLine = arrList[i + 13];
                            travelEmail = arrList[i + 14];
                            if (!string.IsNullOrEmpty(travelHolderName) && !string.IsNullOrEmpty(travelHolderType) && !string.IsNullOrEmpty(travelHolderNo) && com.loto.Common.TypeParse.isDate(travelHolderBirth) && !string.IsNullOrEmpty(travelHolderGender) && !string.IsNullOrEmpty(travelInsuredNo) && !string.IsNullOrEmpty(travelInsuredName) && !string.IsNullOrEmpty(travelInsuredType) && com.loto.Common.TypeParse.isDate(travelInsuredBirth) && !string.IsNullOrEmpty(travelInsuredGender) && com.loto.Common.TypeParse.isDate(travelFromPeriod) && com.loto.Common.TypeParse.IsNumeric(travelCount))
                            {
                                travelHolderAge = DateTime.Now.Year - Convert.ToDateTime(travelHolderBirth).Year;
                                travelInsuredAge = DateTime.Now.Year - Convert.ToDateTime(travelInsuredBirth).Year;
                                if ((travelHolderAge > productAgeMin || travelHolderAge == productAgeMin) && (travelHolderAge < productAgeMax || travelHolderAge == productAgeMax))
                                {
                                    if ((travelInsuredAge > productAgeMin || travelInsuredAge == productAgeMin) && (travelInsuredAge < productAgeMax || travelInsuredAge == productAgeMax))
                                    {
                                        if (productQuota != 0 && Convert.ToInt16(travelCount) > productQuota)
                                        {
                                            isNull = false;
                                            response = "count";
                                            break;
                                        }
                                        else
                                        {
                                            isNull = true;
                                            string policyRow = "{0}^^^^{1}^^^^{2}^^^^{3}^^^^{4}^^^^{5}^^^^{6}^^^^{7}^^^^{8}^^^^{9}^^^^{10}^^^^{11}^^^^{12}^^^^{13}^^^^{14}";
                                            policyRow = string.Format(policyRow, travelHolderName, travelHolderType, travelHolderNo, travelHolderBirth, travelHolderGender, travelInsuredName, travelInsuredType, travelInsuredNo, travelInsuredBirth, travelInsuredGender, travelInsuredTel, travelFromPeriod, travelCount, travelLine, travelEmail);
                                            policyList.Add(policyRow);
                                            totalPrice += Convert.ToInt32(travelCount) * productPrice;
                                        }
                                    }
                                    else
                                    {
                                        isNull = false;
                                        response = "age";
                                        break;
                                    }
                                }
                                else
                                {
                                    isNull = false;
                                    response = "age";
                                    break;
                                }
                            }
                            else
                            {
                                response = "absence";
                                isNull = false;
                                break;
                            }
                        }
                        break;
                }
                if (isNull)
                {
                    List<RequestFuncParams> list = new List<RequestFuncParams>();
                    list.Add(new RequestFuncParams("orderCustFid", CustId.ToString()));
                    list.Add(new RequestFuncParams("productId", productId));
                    list.Add(new RequestFuncParams("policyInfo", string.Join("||||", policyList.ToArray())));
                    BaseService service = new BaseService();
                    ParserXml parserXml = service.RequestEntryService(Dict.ERequestFunc.ADD_ORDER_INFO, list);
                    if (parserXml != null && parserXml.RowsCount > 0)
                    {
                        orderId = parserXml["OrderId", 0];
                        orderNo = parserXml["OrderNo", 0];
                        response = orderId;
                    }
                }
            }
            else
            {
                response = "absence";
            }
        }

        ///<summary>
        ///上传文件
        ///</summary>
        private void UploadAirExcelFile()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""type"":""{0}"",""name"":""{1}"",""no"":""{2}"",""birth"":""{3}"",""gender"":""{4}"",""name1"":""{5}"",""type1"":""{6}"",""no1"":""{7}"",""birth1"":""{8}"",""gender1"":""{9}"",""tel"":""{10}"",""per"":""{11}"",""count"":""{12}"",""flight"":""{13}"",""email"":""{14}""}}";
            var flist = Request.Files;
            string policyType = f("pt");
            for (int i = 0; i < flist.Count; i++)
            {
                string filePath = ConfigurationManager.AppSettings["ExcelFilePath"];
                var cc = flist[i];
                filePath = Path.Combine(filePath, cc.FileName);
                cc.SaveAs(filePath);
                string holderName = string.Empty;
                string holderType = string.Empty;
                string holderNo = string.Empty;
                string holderBirth = string.Empty;
                string holderGender = string.Empty;


                string insuredName = string.Empty;
                string insuredType = string.Empty;
                string insuredNo = string.Empty;
                string insuredBirth = string.Empty;
                string insuredGender = string.Empty;

                string insuredTel = string.Empty;
                string fromPeriod = string.Empty;//起期日期
                string count = string.Empty;//购买份数      
                string flightNo = string.Empty;
                string email = string.Empty;
                List<string> dataList = new List<string>();
                try
                {
                    Workbook wb = new Workbook(cc.InputStream);

                    foreach (Worksheet ws in wb.Sheets)
                    {
                        for (uint r = 6; r <= ws.Rows.MaxRow; ++r)
                        {
                            Row row = ws.Rows[(ushort)r];
                            if (row != null)
                            {
                                if (row.Cells.MaxCol < 15)
                                    break;
                                holderName = row.Cells[10] == null || row.Cells[10].Value == null ? string.Empty : row.Cells[10].Value.ToString();
                                holderType = row.Cells[11] == null || row.Cells[11].Value == null ? string.Empty : row.Cells[11].Value.ToString();
                                holderNo = row.Cells[12] == null || row.Cells[12].Value == null ? string.Empty : row.Cells[12].Value.ToString();
                                holderBirth = row.Cells[13] == null || row.Cells[13].Value == null ? string.Empty : DateTime.FromOADate(Convert.ToInt32(row.Cells[13].Value.ToString())).ToString("yyyy-MM-dd");
                                holderGender = row.Cells[14] == null || row.Cells[14].Value == null ? string.Empty : row.Cells[14].Value.ToString();
                                insuredName = row.Cells[1] == null || row.Cells[1].Value == null ? string.Empty : row.Cells[1].Value.ToString();
                                insuredType = row.Cells[2] == null || row.Cells[2].Value == null ? string.Empty : row.Cells[2].Value.ToString();
                                insuredNo = row.Cells[3] == null || row.Cells[3].Value == null ? string.Empty : row.Cells[3].Value.ToString();
                                insuredBirth = row.Cells[4] == null || row.Cells[4].Value == null ? string.Empty : DateTime.FromOADate(Convert.ToInt32(row.Cells[4].Value.ToString())).ToString("yyyy-MM-dd");
                                insuredGender = row.Cells[5] == null || row.Cells[5].Value == null ? string.Empty : row.Cells[5].Value.ToString();
                                insuredTel = row.Cells[8] == null || row.Cells[8].Value == null ? string.Empty : row.Cells[8].Value.ToString();
                                fromPeriod = row.Cells[7] == null || row.Cells[7].Value == null ? string.Empty : DateTime.FromOADate(Convert.ToInt32(row.Cells[7].Value.ToString())).ToString("yyyy-MM-dd");
                                count = "1";
                                flightNo = row.Cells[6] == null || row.Cells[6].Value == null ? string.Empty : row.Cells[6].Value.ToString();
                                email = row.Cells[9] == null || row.Cells[9].Value == null ? string.Empty : row.Cells[9].Value.ToString();
                                if (!string.IsNullOrEmpty(holderName) && !string.IsNullOrEmpty(holderType) && !string.IsNullOrEmpty(holderNo) && com.loto.Common.TypeParse.isDate(holderBirth) && !string.IsNullOrEmpty(holderGender) && !string.IsNullOrEmpty(insuredNo) && !string.IsNullOrEmpty(insuredName) && !string.IsNullOrEmpty(insuredType) && com.loto.Common.TypeParse.isDate(insuredBirth) && !string.IsNullOrEmpty(insuredGender) && com.loto.Common.TypeParse.isDate(fromPeriod) && com.loto.Common.TypeParse.IsNumeric(count))
                                {
                                    dataList.Add(string.Format(dataFormat, holderType, holderName, holderNo, holderBirth, holderGender, insuredName, insuredType, insuredNo, insuredBirth, insuredGender, insuredTel, fromPeriod, count, flightNo, email));
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
                catch (Exception ex)
                {
                    result = string.Format(resultFormat, ex.Message, "");
                }
                finally
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
            }
            response = result;
        }

        private void UploadTravelExcelFile()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""type"":""{0}"",""name"":""{1}"",""no"":""{2}"",""birth"":""{3}"",""gender"":""{4}"",""name1"":""{5}"",""type1"":""{6}"",""no1"":""{7}"",""birth1"":""{8}"",""gender1"":""{9}"",""tel"":""{10}"",""per"":""{11}"",""count"":""{12}"",""travel"":""{13}"",""email"":""{14}""}}";
            var flist = Request.Files;
            string policyType = f("pt");
            for (int i = 0; i < flist.Count; i++)
            {
                string filePath = ConfigurationManager.AppSettings["ExcelFilePath"];
                var cc = flist[i];
                filePath = Path.Combine(filePath, cc.FileName);
                cc.SaveAs(filePath);
                string holderName = string.Empty;
                string holderType = string.Empty;
                string holderNo = string.Empty;
                string holderBirth = string.Empty;
                string holderGender = string.Empty;


                string insuredName = string.Empty;
                string insuredType = string.Empty;
                string insuredNo = string.Empty;
                string insuredBirth = string.Empty;
                string insuredGender = string.Empty;

                string insuredTel = string.Empty;
                string fromPeriod = string.Empty;//起期日期
                string count = string.Empty;//购买份数      
                string travel = string.Empty;
                string email = string.Empty;
                List<string> dataList = new List<string>();
                try
                {
                    Workbook wb = new Workbook(cc.InputStream);

                    foreach (Worksheet ws in wb.Sheets)
                    {
                        for (uint r = 6; r <= ws.Rows.MaxRow; ++r)
                        {
                            Row row = ws.Rows[(ushort)r];
                            if (row != null)
                            {
                                if (row.Cells.MaxCol < 15)
                                    break;
                                holderName = row.Cells[10] == null || row.Cells[10].Value == null ? string.Empty : row.Cells[10].Value.ToString();
                                holderType = row.Cells[11] == null || row.Cells[11].Value == null ? string.Empty : row.Cells[11].Value.ToString();
                                holderNo = row.Cells[12] == null || row.Cells[12].Value == null ? string.Empty : row.Cells[12].Value.ToString();
                                holderBirth = row.Cells[13] == null || row.Cells[13].Value == null ? string.Empty : DateTime.FromOADate(Convert.ToInt32(row.Cells[13].Value.ToString())).ToString("yyyy-MM-dd");
                                holderGender = row.Cells[14] == null || row.Cells[14].Value == null ? string.Empty : row.Cells[14].Value.ToString();
                                insuredName = row.Cells[1] == null || row.Cells[1].Value == null ? string.Empty : row.Cells[1].Value.ToString();
                                insuredType = row.Cells[2] == null || row.Cells[2].Value == null ? string.Empty : row.Cells[2].Value.ToString();
                                insuredNo = row.Cells[3] == null || row.Cells[3].Value == null ? string.Empty : row.Cells[3].Value.ToString();
                                insuredBirth = row.Cells[4] == null || row.Cells[4].Value == null ? string.Empty : DateTime.FromOADate(Convert.ToInt32(row.Cells[4].Value.ToString())).ToString("yyyy-MM-dd");
                                insuredGender = row.Cells[5] == null || row.Cells[5].Value == null ? string.Empty : row.Cells[5].Value.ToString();
                                insuredTel = row.Cells[8] == null || row.Cells[8].Value == null ? string.Empty : row.Cells[8].Value.ToString();
                                fromPeriod = row.Cells[7] == null || row.Cells[7].Value == null ? string.Empty : DateTime.FromOADate(Convert.ToInt32(row.Cells[7].Value.ToString())).ToString("yyyy-MM-dd");
                                count = "1";
                                travel = row.Cells[6] == null || row.Cells[6].Value == null ? string.Empty : row.Cells[6].Value.ToString();
                                email = row.Cells[9] == null || row.Cells[9].Value == null ? string.Empty : row.Cells[9].Value.ToString();
                                if (!string.IsNullOrEmpty(holderName) && !string.IsNullOrEmpty(holderType) && !string.IsNullOrEmpty(holderNo) && com.loto.Common.TypeParse.isDate(holderBirth) && !string.IsNullOrEmpty(holderGender) && !string.IsNullOrEmpty(insuredNo) && !string.IsNullOrEmpty(insuredName) && !string.IsNullOrEmpty(insuredType) && com.loto.Common.TypeParse.isDate(insuredBirth) && !string.IsNullOrEmpty(insuredGender) && com.loto.Common.TypeParse.isDate(fromPeriod) && com.loto.Common.TypeParse.IsNumeric(count))
                                {
                                    dataList.Add(string.Format(dataFormat, holderType, holderName, holderNo, holderBirth, holderGender, insuredName, insuredType, insuredNo, insuredBirth, insuredGender, insuredTel, fromPeriod, count, travel, email));
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
                catch (Exception ex)
                {
                    result = string.Format(resultFormat, ex.Message, "");
                }
                finally
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
            }
            response = result;
        }
        //取消订单
        private string CancelOrder()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string orderId = q("orderId");
            List<RequestFuncParams> list = new List<RequestFuncParams>();
            list.Add(new RequestFuncParams("orderId", orderId));
            list.Add(new RequestFuncParams("custFid", CustId.ToString()));
            BaseService service = new BaseService();
            ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.CANCEL_ORDER_INFO, list);
            if (parser != null && parser["returnargs", 0] == "1")
            {
                msg = "suc";
            }
            else
            {
                msg = "err";
            }
            return string.Format(resultFormat, msg);
        }
        /// <summary>
        /// 退保
        /// </summary>
        /// <returns></returns>
        private string CancelPolicy()
        {
            string resultFormat = @"{{""msg"":""{0}""}}";
            string msg = string.Empty;
            string orderId = q("orderId");
            string policyId = q("policyId");
            DateTime time = Convert.ToDateTime(com.loto.Common.Utils.UrlDecode(q("time")));
            if (DateTime.Now <= time)
            {
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("orderId", orderId));
                list.Add(new RequestFuncParams("policyId", policyId));
                list.Add(new RequestFuncParams("custFid", CustId.ToString()));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.DO_CANCEL_POLICY, list);
                if (parser != null && parser.RowsCount > 0)
                {
                    if (parser["returnargs", 0] == "true")
                    {
                        msg = "suc";
                    }
                    else
                    {
                        msg = "err";
                    }
                }
                else
                {
                    msg = "err";
                }
            }
            else
            {
                msg = "time";
            }
            return string.Format(resultFormat, msg);
        }

        private void GetPolicyProblem()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""problem"":""{0}""}}";

            string pid = q("pid");
            if (!string.IsNullOrEmpty(pid))
            {
                string policyMemo = string.Empty;
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("policyId", pid));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_POLICY_FLOW, list);
                if (parser != null && parser.RowsCount > 0)
                {
                    policyMemo = parser["FlowMemo", 0];
                }
                List<string> dataList = new List<string>();
                dataList.Add(string.Format(dataFormat, policyMemo));
                result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
            }
            else
            {
                result = string.Format(resultFormat, "err", "");
            }
            response = result;
        }
        /// <summary>
        /// 根据省份查询城市
        /// </summary>
        private void GetCityListByProvinceId()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""id"":""{0}"",""name"":""{1}""}}";

            string provinceId = q("provinceId");
            if (!string.IsNullOrEmpty(provinceId))
            {
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("provinceId", provinceId));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_CITY_LIST_BY_PROVINCE_ID, list);
                List<string> dataList = new List<string>();
                if (parser != null && parser.RowsCount > 0)
                {
                    for (int i = 0; i < parser.RowsCount; i++)
                    {
                        dataList.Add(string.Format(dataFormat, parser["ID", i], parser["Name", i]));
                    }
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
                else
                {
                    result = string.Format(resultFormat, "err", "");
                }
            }
            response = result;
        }
        /// <summary>
        /// 用户提交申领
        /// </summary>
        /// <returns></returns>
        private string AddInvoiceOrder()
        {
            string resultFormat = @"{{""msg"":""{0}"",""orderId"":""{1}""}}";
            string msg = string.Empty;
            string orderId = string.Empty;
            string policy = q("policy");
            string count = q("count");
            string shipping = q("shipping");
            string province = querystring("province");
            string city = querystring("city");
            string address = querystring("address");
            string contacts = querystring("contacts");
            string contactsTel = querystring("contactsTel");
            string money = querystring("money");
            if (!string.IsNullOrEmpty(policy) && !string.IsNullOrEmpty(count) && !string.IsNullOrEmpty(shipping) && !string.IsNullOrEmpty(money))
            {
                string provinceName = string.Empty;
                if (shipping == "3")
                {
                    city = string.Empty;
                    address = string.Empty;
                    contacts = string.Empty;
                    contactsTel = string.Empty;
                }
                else
                {
                    string[] str = province.Split('|');
                    if (str.Length > 0)
                    {
                        provinceName = str[2];
                    }
                }
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("productId", policy));
                list.Add(new RequestFuncParams("count", count));
                list.Add(new RequestFuncParams("shipping", shipping.ToString()));
                list.Add(new RequestFuncParams("province", provinceName));
                list.Add(new RequestFuncParams("city", city));
                list.Add(new RequestFuncParams("address", address));
                list.Add(new RequestFuncParams("contacts", contacts));
                list.Add(new RequestFuncParams("contactsTel", contactsTel));
                list.Add(new RequestFuncParams("money", money));
                list.Add(new RequestFuncParams("custFid", CustId.ToString()));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.ADD_INVOICE_ORDER, list);
                if (parser != null && parser.RowsCount > 0)
                {
                    if (Convert.ToInt64(parser["returnargs", 0]) > 0)
                    {
                        msg = "suc";
                        orderId = parser["returnargs", 0];
                    }
                    else
                    {
                        msg = "err";
                    }
                }
                else
                {
                    msg = "err";
                }
            }
            return string.Format(resultFormat, msg, orderId);
        }
        /// <summary>
        /// 查询配送地址
        /// </summary>
        private void GetOrderAddress()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""province"":""{0}"",""city"":""{1}"",""address"":""{2}"",""contact"":""{3}"",""tel"":""{4}""}}";

            string orderId = q("oid");
            if (!string.IsNullOrEmpty(orderId))
            {
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("custFid", CustId.ToString()));
                list.Add(new RequestFuncParams("orderId", orderId));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_INVOICE_ORDER_INFO_BY_ID, list);
                List<string> dataList = new List<string>();
                if (parser != null && parser.RowsCount > 0)
                {
                    //string content = parser["OrderProvince", 0] + parser["OrderCity", 0] + parser["OrderAddress", 0] + "  " + parser["OrderContact", 0] + "  " + parser["OrderTel", 0];
                    dataList.Add(string.Format(dataFormat, parser["OrderProvince", 0], parser["OrderCity", 0], parser["OrderAddress", 0], parser["OrderContact", 0], parser["OrderTel", 0]));
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
            }
            else
            {
                result = string.Format(resultFormat, "err", "");
            }
            response = result;
        }
        /// <summary>
        /// 查询物流信息
        /// </summary>
        private void GetOrderFedex()
        {
            string resultFormat = @"{{""msg"":""{0}"",""data"":[{1}]}}";
            string result = string.Empty;
            string dataFormat = @"{{""company"":""{0}"",""no"":""{1}""}}";

            string orderId = q("oid");
            if (!string.IsNullOrEmpty(orderId))
            {
                List<RequestFuncParams> list = new List<RequestFuncParams>();
                list.Add(new RequestFuncParams("custFid", CustId.ToString()));
                list.Add(new RequestFuncParams("orderId", orderId));
                BaseService service = new BaseService();
                ParserXml parser = service.RequestEntryService(Dict.ERequestFunc.GET_INVOICE_ORDER_INFO_BY_ID, list);
                List<string> dataList = new List<string>();
                if (parser != null && parser.RowsCount > 0)
                {
                    //string content = "物流单号：" + parser["OrderFedexNo", 0] + "   " + "物流公司：" + parser["OrderFedex", 0];
                    dataList.Add(string.Format(dataFormat, parser["OrderFedex", 0], parser["OrderFedexNo", 0]));
                    result = string.Format(resultFormat, "suc", string.Join(",", dataList.ToArray()));
                }
            }
            else
            {
                result = string.Format(resultFormat, "err", "");
            }
            response = result;
        }
        //计算充值金额
        private void GetSupplement()
        {
            string resultFormat = @"{{""msg"":""{0}"",""AlipayTotalPayPrice"":{1}}}";
            string result = string.Empty;
            decimal amount = Convert.ToDecimal(q("amount"));
            decimal AlipayTotalPayPrice = ConvertCurrencyPay(amount / (1 - AlipayRate));
            result = string.Format(resultFormat, "suc", AlipayTotalPayPrice);
            response = result;
        }
        //获取querystring
        public string q(string s)
        {
            if (Request.QueryString[s] != null)
            {
                return Server.UrlEncode(Request.QueryString[s]);
            }
            return string.Empty;
        }
        //获取post得到的参数
        protected string f(string s)
        {
            if (Request.Form[s] == null) return string.Empty;
            return Request.Form[s];
        }
        public string querystring(string s)
        {
            if (Request.QueryString[s] != null)
            {
                return Server.UrlDecode(Request.QueryString[s]);
            }
            return string.Empty;
        }
        private string JsonCharFilter(string sourceStr)
        {
            sourceStr = sourceStr.Replace("\\", "\\\\");
            sourceStr = sourceStr.Replace("\b", "\\\b");
            sourceStr = sourceStr.Replace("\t", "\\\t");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\n", "\\\n");
            sourceStr = sourceStr.Replace("\f", "\\\f");
            sourceStr = sourceStr.Replace("\r", "\\\r");
            return sourceStr.Replace("\"", "\\\"");
        }
        public decimal ConvertCurrencyPay(decimal currency)
        {
            decimal concurrency = (decimal)Math.Round(currency, 2);
            decimal thridCurrency = (decimal)Math.Round(currency, 3);
            if (concurrency - thridCurrency < 0)
            {
                concurrency = concurrency + 0.01M;
            }
            return (decimal)Math.Round(concurrency, 2);
        }
    }
}
